package com.hzhk.happyrent.ui.fragment.login;

import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.hzhk.happyrent.R;
import com.hzhk.happyrent.bean.CodeModel;
import com.hzhk.happyrent.bean.login.LoginResponse;
import com.hzhk.happyrent.bean.rent.BaseModel;
import com.hzhk.happyrent.network.API;
import com.hzhk.happyrent.network.HttpManager;
import com.hzhk.happyrent.network.MyBaseSubscriber;
import com.hzhk.happyrent.network.MyStringResponse;
import com.hzhk.happyrent.network.MyStringTransResponse;
import com.hzhk.happyrent.ui.view.ClearEditText;
import com.hzhk.happyrent.utils.MyPerference;
import com.hzhk.happyrent.utils.PatternStringUtirl;
import com.hzhk.happyrent.utils.StringUtils;
import com.tamic.novate.Throwable;


import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link RegisterFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class RegisterFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.reg_act_user_phone)
    ClearEditText regActUserPhone;
    @BindView(R.id.reg_vcode)
    ClearEditText regVcode;
    @BindView(R.id.btn_sendvcode)
    Button btnSendvcode;
    @BindView(R.id.reg_act_user_pwd)
    ClearEditText regActUserPwd;
    @BindView(R.id.btn_register)
    Button btnRegister;
    Unbinder unbinder;
    @BindView(R.id.iv_see_pwd)
    ImageView ivSeePwd;
    @BindView(R.id.act_login_layout)
    LinearLayout actLoginLayout;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private TimeCount time;

    public RegisterFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment RegisterFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static RegisterFragment newInstance(String param1, String param2) {
        RegisterFragment fragment = new RegisterFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_register, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    private void initView() {
        regActUserPhone.addTextChangedListener(new TextChange(1));
        regActUserPwd.addTextChangedListener(new TextChange(1));
        regVcode.addTextChangedListener(new TextChange(2));
        ivSeePwd.setTag(false);
        time = new TimeCount(59200, 100);
        btnSendvcode.setEnabled(false);
        btnRegister.setEnabled(false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public void showToast(int id) {
        Toast.makeText(getContext(), id, Toast.LENGTH_SHORT).show();
    }

    @OnClick({R.id.btn_sendvcode, R.id.btn_register})
    public void onViewClicked(View view) {
        String phone = regActUserPhone.getText().toString().trim();
        String vcode = regVcode.getText().toString().trim();
        String pwd = regActUserPwd.getText().toString().trim();
        switch (view.getId()) {
            case R.id.btn_sendvcode:
                getVCode(phone);
                break;
            case R.id.btn_register:
                register(phone, pwd, vcode);
                break;
        }
    }

    private void register(final String phone, final String pwd, String vcode) {
        Map<String, Object> params = new HashMap<>();
        params.put("phone", phone);
        params.put("code", vcode);
        params.put("password", pwd);
        HttpManager.getInstance().perform_post(API.REGISTER, params, new MyStringResponse(getContext()) {
            @Override
            public void onNext(Object tag,String response) {
                CodeModel codeModel = new Gson().fromJson(response, CodeModel.class);

                if (codeModel.getErrCode() == 0) {
                    LoginResponse baseModel = new Gson().fromJson(response, LoginResponse.class);
//                    Toast.makeText(getContext(),baseModel.getMessage()+"",Toast.LENGTH_SHORT).show();
                    MyPerference.getInstance().setUserInfoSave(baseModel.getData().getUser_info().getId(), phone, pwd, baseModel.getData().getUser_info().getIs_auth());
                    ((Activity) getContext()).finish();
                } else {
                    Toast.makeText(getContext(), codeModel.getMessage() + "", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Object tag, Throwable e) {
//                Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }

        });
    }

    private void getVCode(String phone) {
        Map<String, Object> params = new HashMap<>();
        params.put("phone", phone);
        HttpManager.getInstance().perform_post(API.SMS_SEND, params, new MyStringResponse(getContext()) {
            @Override
            public void onNext(Object tag,String response) {
                CodeModel baseModel = new Gson().fromJson(response, CodeModel.class);
                if (0 == baseModel.getErrCode()) {
                    Toast.makeText(getContext(), R.string.apply_success, Toast.LENGTH_SHORT).show();
                    time.start();
                } else {
                    Toast.makeText(getContext(), baseModel.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Object tag, Throwable e) {
//                Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(Object tag, Throwable e) {

            }
        });
    }

    @OnClick(R.id.iv_see_pwd)
    public void onViewClicked() {
        boolean tag = (Boolean) ivSeePwd.getTag();
        if (tag) {
            ivSeePwd.setImageResource(R.drawable.pwd_disvisible);
            ivSeePwd.setTag(false);
            regActUserPwd
                    .setTransformationMethod(PasswordTransformationMethod
                            .getInstance());
            regActUserPwd.setSelection(regActUserPwd.getText()
                    .toString().trim().length());
        } else {
            ivSeePwd.setImageResource(R.drawable.pwd_visible);
            ivSeePwd.setTag(true);
            regActUserPwd
                    .setTransformationMethod(HideReturnsTransformationMethod
                            .getInstance());
            regActUserPwd.setSelection(regActUserPwd.getText()
                    .toString().trim().length());
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    // EditText监听器
    class TextChange implements TextWatcher {
        private int flags = 0;

        public TextChange(int flags) {
            this.flags = flags;
        }

        @Override
        public void afterTextChanged(Editable arg0) {
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                                      int arg3) {
        }

        @Override
        public void onTextChanged(CharSequence cs, int start, int before,
                                  int count) {
            boolean Sign1 = regActUserPhone.getText().length() > 10;
            boolean Sign2 = regActUserPwd.getText().length() > 5;
            boolean Sign3 = regVcode.getText().length() > 3;
            if (flags == 1) {

                if (Sign1 & Sign2) {
                    btnSendvcode
                            .setBackgroundDrawable(getResources().getDrawable(R.drawable.img_time_tick_w));
                    btnSendvcode.setTextColor(getResources().getColor(R.color.black_60));
                    btnSendvcode.setEnabled(true);
                } else {
                    // 在layout文件中，对Button的text属性应预先设置默认值，否则刚打开程序的时候Button是无显示的
                    btnSendvcode
                            .setBackgroundDrawable(getResources().getDrawable(R.drawable.img_time_tick_g));
                    btnSendvcode.setTextColor(getResources().getColor(R.color.white_90));
                    btnSendvcode.setEnabled(false);
                }

            }
            if (Sign1 & Sign2 & Sign3) {
                btnRegister.setBackgroundResource(R.drawable.btn_red_selector);
                btnRegister.setEnabled(true);
            } else {
                // 在layout文件中，对Button的text属性应预先设置默认值，否则刚打开程序的时候Button是无显示的
                btnRegister.setEnabled(false);
            }

        }
    }

    // 验证码倒计时
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {// 计时完毕时触发
            btnSendvcode.setText(R.string.get_again);
            btnSendvcode.setEnabled(true);
            btnSendvcode.setBackgroundDrawable(getResources().getDrawable(R.drawable.img_time_tick_w));
            btnSendvcode.setTextColor(getResources().getColor(R.color.black_60));
            boolean Sign1 = regActUserPhone.getText().length() > 10;
            boolean Sign2 = regActUserPwd.getText().length() > 5;
            boolean Sign3 = regVcode.getText().length() > 3;
            if (Sign1 & Sign2) {
                btnSendvcode
                        .setBackgroundDrawable(getResources().getDrawable(R.drawable.img_time_tick_w));
                btnSendvcode.setTextColor(getResources().getColor(R.color.black_60));
                btnSendvcode.setEnabled(true);
            } else {
                // 在layout文件中，对Button的text属性应预先设置默认值，否则刚打开程序的时候Button是无显示的
                btnSendvcode
                        .setBackgroundDrawable(getResources().getDrawable(R.drawable.img_time_tick_g));
                btnSendvcode.setTextColor(getResources().getColor(R.color.white_90));
                btnSendvcode.setEnabled(false);
            }
            if (Sign1 & Sign2 & Sign3) {
                btnRegister.setBackgroundDrawable(getResources().getDrawable(R.drawable.btn_red_selector));
                btnRegister.setEnabled(true);
            } else {
                // 在layout文件中，对Button的text属性应预先设置默认值，否则刚打开程序的时候Button是无显示的
                btnRegister.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_btn_gray_solid));
                btnRegister.setEnabled(false);
            }

        }

        @Override
        public void onTick(long millisUntilFinished) {// 计时过程显示
            btnSendvcode.setBackgroundDrawable(getResources().getDrawable(R.drawable.img_time_tick_g));
            btnSendvcode.setTextColor(getResources().getColor(R.color.white_90));
            btnSendvcode.setEnabled(false);
            btnSendvcode.setText((millisUntilFinished + 800) / 1000 + "s");
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        time.cancel();
    }
}
